# -*- coding:utf-8 -*-

from WebautoTest.base.base_element_enmu import Element as Ele
from selenium.webdriver.support.ui import WebDriverWait
import selenium.common.exceptions

"""
作用：
1.判断页面元素是否存在
2.操作页面元素
"""


class Packelement:
    def __init__(self, driver=""):
        self.driver = driver

    def find_element(self, case):
        try:
            if case.get("ele_way", 0) != 0:
                WebDriverWait(self.driver, timeout=10).until(lambda x: self.elements_by(case))
        except selenium.common.exceptions.TimeoutException:
            print("==查找元素超时==")
            return {False, "==查找元素超时=="}
        except selenium.common.exceptions.NoSuchElementException:
            print("==查找元素不存在==")
            return {False, "==查找元素不存在=="}
        except selenium.common.exceptions.WebDriverException:
            print("WebDriver出现问题了")
            return {False, "WebDriver出现问题了"}

    def click(self, case):
        if case["find_type"] == Ele.find_element_by_id or case["find_type"] == Ele.find_element_by_xpath \
                or Ele.find_element_by_css_selector or case["find_type"] == Ele.find_element_by_class_name or \
                case["find_type"] == Ele.find_element_by_link_text:
            self.elements_by(case).click()
        elif case.get("find_type") == Ele.find_elements_by_id:
            self.elements_by(case)[case["index"]].click()
        return True

    def send_keys(self, case):
        if case["operate_type"] == Ele.send_keys:
            self.elements_by(case).send_keys(case["msg"])
        return True

    def switch_frame(self, case):
        if case["find_type"] == Ele.switch_to_frame:
            iframe = case['ele_way']
            self.driver.switch_to.frame(iframe)
        return True

    def gather_ele(self, case):
        self.find_element(case)
        self.click(case)
        self.switch_frame(case)
        self.send_keys(case)
        return True

    def elements_by(self, case):
        elements = {
            Ele.find_element_by_id: lambda: self.driver.find_element_by_id(case["ele_way"]),
            Ele.find_element_by_xpath: lambda: self.driver.find_element_by_xpath(case["ele_way"]),
            Ele.find_element_by_class_name: lambda: self.driver.find_element_by_class_name(case['ele_way']),
            Ele.find_elements_by_id: lambda: self.driver.find_elements_by_id(case['ele_way']),
            Ele.find_element_by_css_selector: lambda: self.driver.find_element_by_css_selector(case['ele_way']),
            Ele.find_element_by_link_text: lambda: self.driver.find_element_by_link_text(case['ele_way'])

        }
        return elements[case["find_type"]]()
